import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';

import '../../common/model/chat/chat.dart';

class Cell extends StatelessWidget {
  final ChatModel model;
  const Cell({super.key, required this.model});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: model.isMe
          ? MainAxisAlignment.end
          : MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        model.isMe ? Container(width: 80.w) : _AvatarView(chat: model),
        Flexible(child: buildBubble(), fit: FlexFit.loose),
        !model.isMe ? Container(width: 80.w) : _AvatarView(chat: model),
      ],
    );
  }

  Widget buildBubble() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(!model.isMe ? 0 : 8.sp),
          topRight: Radius.circular(!model.isMe ? 8.sp : 0),
          bottomLeft: Radius.circular(8.sp),
          bottomRight: Radius.circular(8.sp),
        ),
        color: model.isMe ? Color(0xFF7980F9) : Colors.white,
      ),
      padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
      margin: EdgeInsets.only(top: 15.w, right: 10.w),
      child: model.isThinking
          ? _ThinkingView()
          : Text(
              model.toString(),
              style: TextStyle(
                color: model.isMe ? Colors.white : Colors.black,
                fontSize: 15.sp,
              ),
            ),
    );
  }
}

class _ThinkingView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Lottie.asset(
          "assets/images/loading_lottie.json",
          width: 55.w,
          height: 55.w,
        ),
      ],
    );
  }
}

class _AvatarView extends StatelessWidget {
  final ChatModel chat;

  String get avatar {
    if (chat.isMe) {
      return "assets/images/avatar_usr.png";
    } else {
      return "assets/images/avatar_bot.png";
    }
  }

  const _AvatarView({super.key, required this.chat});

  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Container(width: 40.w, child: Image.asset(avatar)),
    );
  }
}
